package com.qf.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.entity.dto.Orders;
import com.qf.entity.po.LoginMerchant;
import com.qf.entity.vo.OrderVo;
import com.qf.mapper.OrderMapper;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class OrderService extends ServiceImpl<OrderMapper, Orders> {
    private final static SimpleDateFormat SIMPLE_DATE_FORMAT = new SimpleDateFormat("yyyyMMddHHmmss");
    @Transactional(readOnly = true)
    public int getBuyNumByGoodsId(Long goodsId) {
        QueryWrapper<Orders> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(Orders::getGoodsId, goodsId);
        return this.count(wrapper);
    }

    @Transactional
    public void saveOrder(Orders order, LoginMerchant loginMerchant) {
        order.setMerchantUserId(loginMerchant.getId());
        order.setOrderId(String.format("%s%s%s",
                SIMPLE_DATE_FORMAT.format(new Date()),  //时间戳
                loginMerchant.getId(), //商户id
                RandomUtils.nextInt(10000, 100000) //五位随机数
        )); //订单号
        order.setPrice(1); //单位分
        order.setPayState(Orders.OrderState.NON_PAY.getCode()); //未支付
        this.save(order);
    }

    @Transactional(readOnly = true)
    public List<OrderVo> getOrderByMerchantId(Long merchantUserId) {
        return this.baseMapper.getOrderByMerchantId(merchantUserId);
    }


    @Transactional
    public Boolean updatePayState(String orderId, Orders.OrderState payState) {
        UpdateWrapper<Orders> wrapper = new UpdateWrapper<>();
        wrapper.lambda()
                .eq(Orders::getOrderId, orderId) //where order_id = #{orderId}
                .set(Orders::getPayState, payState.getCode()); //set pay_state=#{payState}
        return this.update(wrapper);
    }
}
